package com.liyuxiang.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liyuxiang.domain.LoginUser;
import com.liyuxiang.domain.ResponseResult;
import com.liyuxiang.pojo.entity.User;
import com.liyuxiang.utils.JwtUtil;
import com.liyuxiang.utils.RedisCache;
import com.liyuxiang.utils.WebUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.codec.DecodingException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        System.out.println(request.getRequestURI());
        if (!StringUtils.hasText(token)) {
//            if (request.getRequestURI().equals("/user/login")) {
//                //放行
//                filterChain.doFilter(request, response);
//                return;
//            }
//            ResponseResult responseResult = new ResponseResult<Object>(400, "请先登录");
//            response.setContentType("application/json");
//            response.setCharacterEncoding("UTF-8");
//            String s = new ObjectMapper().writeValueAsString(responseResult);
//            response.getWriter().write(s);
//            return;
            filterChain.doFilter(request, response);
            return;
        }
        //解析token   取出用户的id
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (ExpiredJwtException e) {
            response(response, 401, "此token已过期");
            return;
        } catch (DecodingException e) {
            response(response, 401, "token错误");
            return;
        } catch (MalformedJwtException e) {
            response(response, 401, "token校验失败");
            return;
        } catch (SignatureException e) {
            response(response, 401, "非有效的token");
            return;
        } catch (Exception e) {
            response(response, 401, "token未知异常");
            return;
        }

        UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter = new UsernamePasswordAuthenticationFilter();


        System.out.println(userId);

        //根据用户id从redis中查询用户完整信息
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);
        System.out.println(loginUser);
        if (Objects.isNull(loginUser)) {
//            ResponseResult responseResult = new ResponseResult<Object>(400, "请先登录");
//            response.setContentType("application/json");
//            response.setCharacterEncoding("UTF-8");
//            String s = new ObjectMapper().writeValueAsString(responseResult);
//            response.getWriter().write(s);
//            return;
            throw new RuntimeException("用户未登录");
        }


        //存入SecurityContextHolder
        //TODO  获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }


    //处理token校验失败异常返回
    private void response(ServletResponse servletResponse, int code, String message) {
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        ResponseResult resultData = new ResponseResult();
        resultData.setCode(code);
        resultData.setMsg(message);
        String errMsg = JSON.toJSONString(resultData);
        res.setStatus(code);
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json");
        try {
            res.getOutputStream().write(errMsg.getBytes(StandardCharsets.UTF_8));
            res.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
